package com.xiu.java8.stream;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
//stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|
public class StreamTest {

	public static void main(String[] args) {
		//生成流
		List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
		List<String> collect = strings.stream().filter(string->!string.isEmpty()).collect(Collectors.toList());
		//forEach迭代流中的每个数据
		System.out.println("forEach迭代流中的每个数据");
		collect.forEach(string->System.out.println(string));
		collect.forEach(System.out::println);
		Random random = new Random();
		random.ints().limit(10).forEach(System.out::println);
		List<Integer> numbers = Arrays.asList(-3, 1, -2, 3, 7, 3, 5);
		//map 方法用于映射每个元素到对应的结果
		// 获取对应的平方数
		System.out.println("map 方法用于映射每个元素到对应的结果");
		List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
		squaresList.forEach(System.out::println);
		//filter 方法用于通过设置的条件过滤出元素
		System.out.println("filter 方法用于通过设置的条件过滤出元素");
		strings.stream().filter(string->!string.isEmpty()).forEach(System.out::println);;
		//limit 方法用于获取指定数量的流
		System.out.println("limit 方法用于获取指定数量的流");
		random.ints().limit(10).forEach(System.out::println);
		//sorted 方法用于对流进行排序
		System.out.println("sorted 方法用于对流进行排序");
		random.ints().limit(10).sorted().forEach(System.out::println);
		numbers.stream().filter(i->i>0).sorted().map(i->i*i).distinct().collect(Collectors.toList()).forEach(System.out::println);;
		//parallelStream 是流并行处理程序的代替方法
		strings.parallelStream().filter(string->!string.isEmpty()).collect(Collectors.toList()).forEach(System.out::println);
		//Collectors 类实现了很多归约操作，例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串：
		List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
		 
		System.out.println("筛选列表: " + filtered);
		String collect2 = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(","));
		System.out.println(collect2);
		//统计
		List<Integer> numbers2 = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
		IntSummaryStatistics summaryStatistics = numbers2.stream().mapToInt(x->x).summaryStatistics();
		System.out.println("getAverage:"+summaryStatistics.getAverage());
		System.out.println("getMin:"+summaryStatistics.getMin());
		System.out.println("getSum:"+summaryStatistics.getSum());
		System.out.println("getMax:"+summaryStatistics.getMax());
		System.out.println("getCount:"+summaryStatistics.getCount());
	}

}
